package com.scalar.chiptrack.finance.creditNote.actionCommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.finance.creditNote.forms.CreditNoteForm;
import com.scalar.chiptrack.finance.creditNote.dao.CreditNoteDAO;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.packingslip.dao.PackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.dao.NewPackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.forms.PackingSlipForm;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * User: Sujan
 * Date: Apr 16, 2007
 * Time: 7:22:26 PM
 */
public class CreditNoteSaveCommand extends ActionCommand
{

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        HttpSession session  = request.getSession();
        User user            = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        CreditNoteForm creditNoteForm = (CreditNoteForm) form;
        HashMap errors = (HashMap)request.getAttribute( SessionKeys.ERROR_MESSAGES );
        HashMap info = (HashMap)request.getAttribute( SessionKeys.INFO_MESSAGES );
        DBTransaction dbTransaction = null;
        boolean success = false;
        try
        {
            dbTransaction = DBTransaction.getInstance();
            dbTransaction.begin();

            if ( CreditNoteDAO.isCreditNoteNoExists( dbTransaction, creditNoteForm.getCreditNoteNumber() ) )
            {
                PackingSlipForm packingSlipForm = NewPackingSlipDAO.loadPackingSlipById( creditNoteForm.getCustomerShippingId() );
                creditNoteForm.setSalesOrderId( packingSlipForm.getSalesOrderId() );
                creditNoteForm.setBillingAddress( packingSlipForm.getBillingAddressObject() );
                creditNoteForm.setShippingAddress( packingSlipForm.getShippingAddressObject() );
                creditNoteForm.setPackingSlipLabel( packingSlipForm.getLabel() );

                SalesOrder salesOrder = SalesOrderDAO.loadSalesOrder( creditNoteForm.getSalesOrderId()+"", dbTransaction );
                creditNoteForm.setCustomerName( salesOrder.getCustomerName() );
                creditNoteForm.setSalesOrderNo( salesOrder.getSalesOrderNo() );
                creditNoteForm.setCustomerPONo( salesOrder.getCustomerPO() );
                creditNoteForm.setSalesRep( salesOrder.getSalesRep() );
                creditNoteForm.setEndCustomerName( salesOrder.getOdm());
                creditNoteForm.setEndUserName( salesOrder.getEndCustomer() );
                creditNoteForm.setPayTerms( salesOrder.getShippingTerms());

                errors.put( "Credit Note Number already exists", null );
                return mapping.findForward ( "creditNote" );
            }
            else
            {
                int creditNoteId = CreditNoteDAO.saveCreditNote(dbTransaction, creditNoteForm.getCreditNoteNumber(), creditNoteForm.getIssueDate(), creditNoteForm.getSalesOrderId(), user.getUserId(), creditNoteForm.getNoteType(), creditNoteForm.getComments(), creditNoteForm.getCustomerShippingId(), creditNoteForm.getIsUnits()  );
                if ( creditNoteId > 0 )
                {
                    creditNoteForm.setCreditNoteId ( creditNoteId );
                    CreditNoteDAO.saveCreditNoteLineItems ( dbTransaction, creditNoteForm, user.getUserId() );
                    info.put ( "Credit/Debit Note=" + creditNoteForm.getCreditNoteNumber()," saved successfully" );
                    info.put ( "View/Print", "Click here to <a href='javascript:openCreditNoteToView("+creditNoteId+")' onmouseover=\"window.status='Click here to View credit/debit note';return true\" onmouseout=\"window.status='';return true\">view/print</a> Credit/Debit Note" );
                    String approveLink= "/"+ ConfigManager.getChipTracContext()+"/creditNoteAction.do?action="+ Constants.ACTION_APPROVED + "&creditNoteId="+creditNoteId;
                    info.put ( "Approve", "Click here to <a href='" + approveLink + "' onmouseover=\"window.status='Click here to Approve credit/debit note';return true\" onmouseout=\"window.status='';return true\">Approve</a> Credit/Debit Note" );
                    
                    success = true;
                }
            }
        }
        catch ( ScalarException e )
        {
            e.printStackTrace();
            errors.put ( "Could not save Credit Note", null );
        }
        finally
        {
            if ( dbTransaction != null )
            {
                if ( success )
                {
                    dbTransaction.commit();
                }
                else
                {
                    dbTransaction.rollback();
                }
            }
        }

        request.setAttribute ( "customers", CustomerDAO.getAllCustomerNamesByUserType ( null, user ) );
        ArrayList salesOrders = NewSalesOrderDAO.loadShippedSalesOrderNumbersByCustomerId ( null, creditNoteForm.getCustomerId() );
        request.setAttribute ( "salesOrderNumbers", salesOrders );
        creditNoteForm.setCreditNoteNumber("");
        creditNoteForm.setNoteType("0");
        return mapping.findForward ( "search" );
    }
}
